const jwt = require('jsonwebtoken');
module.exports = () => {
    return async (ctx,next) => {
        //除去登录注册，所有的接口都需要做鉴权校验
        let writeArr = ['/api/login','/api/registry'];

        if(writeArr.includes(ctx.request.url)){
            await next();
        }else{
            //需要检验token
            let token = ctx.get('token');
            try{
                jwt.verify(token,'lixd');
                await next();
            }catch(e){

                //把错误信息分类， 是鉴权失败还是其他有误

                if(e.name === 'JsonWebTokenError' || e.name === 'TokenExpiredError'){
                    ctx.status = 401;
                    ctx.body = {
                        code:5,
                        msg:e
                    }
                }else{
                    ctx.body = {
                        code:6,
                        msg:e
                    }
                }
            }
        }
    }
}